#include "pthreadPool.h"

int handleLongCmd(server_t *pserver){
    printf("I am Long cmd.\n");
    int sockFd_long = initTcp();
    int check = 0;
    int times = 0;

    while(1){
        //发送Token
        trainState_t trainState;
        strcpy(trainState.buf,pserver->userName);
        strcat(trainState.buf,pserver->token);
        trainState.state = TOKEN;
        trainState.length = strlen(trainState.buf);
        trainState.preLength = strlen(pserver->userName);
        send(sockFd_long,&trainState,
             sizeof(trainState.length) + sizeof(trainState.state) +
             sizeof(trainState.preLength) + trainState.length,MSG_NOSIGNAL);
        //接收回执
        recvn(sockFd_long ,&check,sizeof(check));
        if(check == 0){
            //验证成功，退出
            break;
        }else if(check == 1){
            printf("Try again!\n");
            encode(pserver->key,pserver->userName,pserver->token);
            ++times;
            if(times == 4){
                //试3次
                close(sockFd_long);
                return -1;
            }
        }
    }
    //验证成功
    printf("cmd = %s\n",pserver->cmd);
    train_t train;
    bzero(&train,sizeof(train));
    train.length = strlen(pserver->cmd);
    strcpy(train.data,pserver->cmd);
    send(sockFd_long,&train,sizeof(train.length) + train.length,MSG_NOSIGNAL);
    if(strncmp("puts",pserver->cmd,4) == 0){
        char file[100] = {0};
        int i = 4;
        while(pserver->cmd[i] == ' '){
            ++i;
        }
        strcpy(file,pserver->cmd + i);
        upload(sockFd_long,file);
    }else{
        download(sockFd_long);
    }
    close(sockFd_long);
    return 0;
} 

